package com.hp.easyBuy.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class QiniuUtils {
     //AK
     private static final String accessKey = "f0Zh_78zHXqldeiL_PvJTJkrnXtniwhVuHooutFo";
     //SK
     private static final String secretKey = "EqWTACtvvB7yit0-UOmW8zJ_6qgiZHIxI-p0tIac";
     //空间
     private static final String bucket = "chenshuai";

     public static R upload(InputStream is,String fileName){
         ObjectMapper mapper = new ObjectMapper();
         Map<String,Object> resultMap=new HashMap<>();
         //构造一个带指定 Region 对象的配置类
         Configuration cfg = new Configuration(Region.huanan());
         UploadManager uploadManager = new UploadManager(cfg);
         //1、获得上传文件扩展名
         String ext=fileName.substring(fileName.lastIndexOf("."));
         //2、重新生成随机名
         String key = UUID.randomUUID().toString()+ext;
         Auth auth = Auth.create(accessKey, secretKey);
         String upToken = auth.uploadToken(bucket);
         try {
             Response response = uploadManager.put(is, key, upToken,null,null);
             //解析上传成功的结果
             DefaultPutRet putRet = mapper.readValue(response.bodyString(), DefaultPutRet.class);

             /*resultMap.put("code","00");
             resultMap.put("msg","图像上传成功");
             resultMap.put("data",putRet.key);*/
             return R.success(putRet.key);

         } catch (Exception ex) {
             return R.error();
         }
     }
}
